import React, { useState, useEffect, useRef } from 'react'
import { Modal, InputItem, Icon, Toast } from 'antd-mobile'
import { getPoolNumber, lockNumber } from '../../request/home'
import './style.scss'

Toast.config({ duration: 2, mask: false })

function SelectPhoneNumber(props) {
  const { visible, close, addressCode, addressText, token, selectNumber, getToken } = props
  const [numberList, setNumberList] = useState([])
  const [searchkey, setSearchkey] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const numberRef = useRef('')

  useEffect(() => {
    getNumbers().catch(e => console.log(e.message))
  }, [])

  useEffect(() => {
    if (!token || !numberRef.current) return
    handleSelectNumber().catch(e => console.log(e.message))
  }, [token, numberRef.current])

  const getNumbers = async() => {
    setIsLoading(true)
    const { code, data } = await getPoolNumber({
      provice_code: addressCode[0],
      provice: addressText[0],
      city_code: addressCode[1],
      city: addressText[1],
      searchkey,
      page: 1,
      size: 10
    })
    setIsLoading(false)
    if (code) {
      Toast.fail('获取号码失败，请稍后再试')
      return false
    }
    let numberList = data || []
    numberList = numberList.map(item => {
      const label = searchkey ? item.replace(searchkey, `<span class="number-search-key">${searchkey}</span>`) : item
      return { label, value: item }
    })

    setNumberList(numberList)
  }

  const handleSelectNumber = async() => {
    const { code } = await lockNumber({ number: numberRef.current, token, province_code: addressCode[0], city_code: addressCode[1] })
    Toast.hide()
    if (code) {
      Toast.fail('锁定号码失败，请稍后再试')
      return false
    }
    selectNumber(numberRef.current)
    numberRef.current = ''
    close()
  }

  const onSelectNumber = number => {
    Toast.loading('锁定号码中', 60, null, true)
    numberRef.current = number
    getToken()
  }

  return (
    <div className="select-phone-number">
      <Modal
        visible={visible}
        transparent
        closable
        maskClosable={false}
        title="选择号码"
        className="select-phone-number--modal"
        onClose={close}
      >
        <div className="search">
          <div className="input">
            <InputItem
              placeholder="生日、幸运数字等"
              type="number"
              onChange={value => setSearchkey(value)}
            />
          </div>
          <div className="button" onClick={getNumbers}>
            <Icon type="search"/>
          </div>
        </div>
        <div className="content">
          {isLoading ? (
            <div className="loading">
              <Icon size="lg" type="loading"/>
            </div>
          ) : (
            numberList.length > 0 ? numberList.map((number, index) => (
              <p
                className="number-item"
                key={index}
                onClick={() => onSelectNumber(number.value)}
              >
                <span dangerouslySetInnerHTML={{ __html: number.label }}></span>
              </p>
            )) : (
              <p className="number-empty">抱歉，没有匹配的号码</p>
            )
          )}
        </div>
        <div className="footer">
          <span onClick={getNumbers}>换一批</span>
        </div>
      </Modal>
    </div>
  )
}

export default SelectPhoneNumber
